package Utils.web;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * UDP工具类
 */
public final class UdpUtils {
    /**
     * sender向receiver发送字符串信息。
     *
     * @param msg         待发送的字符串信息
     * @param socket      DatagramSocket
     * @param inetAddress receiver的InetAddress
     * @param port        receiver的端口号
     * @throws IOException
     */
    public static void senderSendMessageToReceiver(String msg, DatagramSocket socket, InetAddress inetAddress, int port) throws IOException {
        byte[] buf = msg.getBytes();
        DatagramPacket packet = new DatagramPacket(buf, 0, buf.length, inetAddress, port);
        socket.send(packet);
    }

    /**
     * sender向receiver发送字符串信息。
     *
     * @param msg         待发送的字符串信息
     * @param inetAddress receiver的InetAddress
     * @param port        receiver的端口号
     * @throws IOException
     */
    public static void senderSendMessageToReceiver(String msg, InetAddress inetAddress, int port) throws IOException {
        try (DatagramSocket socket = new DatagramSocket();) {
            senderSendMessageToReceiver(msg, socket, inetAddress, port);
        }
    }

    /**
     * receiver从sender接收字符串信息。
     * @param socket
     * @return
     * @throws IOException
     */
    public static String receiverReceiveMessageFromSender(DatagramSocket socket, int bufferSize) throws IOException {
        DatagramPacket packet = receiverReceiveDataFromSender_DP(socket, bufferSize);
        return new String(packet.getData(), 0, packet.getLength());
    }

    /**
     * receiver从sender接收信息，返回DatagramPacket。
     * @param socket 服务器端的DatagramSocket
     * @return 返回DatagramPacket
     * @throws IOException
     */
    public static DatagramPacket receiverReceiveDataFromSender_DP(DatagramSocket socket, int bufferSize) throws IOException {
        byte[] buf = new byte[bufferSize];
        DatagramPacket packet = new DatagramPacket(buf, 0, buf.length);
        socket.receive(packet);
        return packet;
    }

    /**
     * receiver从sender接收信息，返回byte[]。
     * @param socket 服务器端的DatagramSocket
     * @param bufferSize 缓冲区大小
     * @return 返回byte[]
     * @throws IOException
     */
    public static byte[] receiverReceiveDataFromSender_Bytes(DatagramSocket socket, int bufferSize) throws IOException {
        DatagramPacket packet = receiverReceiveDataFromSender_DP(socket, bufferSize);
        return packet.getData();
    }
}
